package com.ruyuan.starter.async.handler;

import com.lmax.disruptor.EventTranslator;
import com.lmax.disruptor.WorkHandler;
import com.ruyuan.starter.async.WorkEventBus;
import com.ruyuan.starter.async.WorkEventBusManager;
import com.ruyuan.starter.async.event.BossEvent;
import com.ruyuan.starter.async.event.WorkEvent;
import com.ruyuan.starter.async.listener.EventListener;

import java.util.List;

/**
 * @author zhonghuashishan
 */
public class BossEventHandler implements WorkHandler<BossEvent> {

    @Override
    public void onEvent(BossEvent event) throws Exception {
        try {
            dispatchBossEvent(event);
        } finally {
            event.clear();
        }
    }

    /**
     * 只做事件分发
     */
    @SuppressWarnings("unchecked")
    private void dispatchBossEvent(BossEvent event) {
        // 1、根据channel获取到对应的workerEventBus
        WorkEventBus workEventBus = WorkEventBusManager.getSingleton().getWorkEventBus(event.channel);
        // 2、根据事件类型获取到对应的listener
        List<EventListener> eventListeners = workEventBus.getEventListeners(event.event);
        // 3、封装workEvent
        EventTranslator<WorkEvent> translator = (e, s) -> {
            e.event = event.event;
            e.context = event.context;
            e.listeners = eventListeners;
        };
        // 4、分发到指定的workerEventBus
        boolean publish = workEventBus.publish(translator);
        if (!publish) {
            System.out.println("workRingbuffer满了 channel=" + event.channel);
        }
    }
}